package com.lancoo.znbkxx.teacher.model

import android.content.Context
import android.util.Log
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.Ext.Companion.BASE_URL
import com.lancoo.znbkxx.teacher.net.BkApiMethods
import io.reactivex.functions.Consumer
import okhttp3.ResponseBody
import java.net.Inet4Address
import java.net.NetworkInterface
import java.net.SocketException

/**
 * auther: 王国龙
 * Date：2019.12.31
 * describe: 管理系统浏览日志
 */
object OperationHelp {
    private val Operations = arrayOf(
            "试卷预览",
            "发布试卷",
            "查看成绩",
            "评阅试卷",
            "评阅完成",
            "讲评保存",
            "讲评完成",
            "查看讲评",
            "查看已巩固")

    fun operationLog(OperationId: Int, context: Context?) {
        val method = BkApiMethods(context)
        val jSONObject = BkApiMethods.createJSONObject()
        jSONObject["ProvinceID"] = Ext.PROVINCE_ID
        jSONObject["CityID"] = Ext.CITY_ID
        jSONObject["CountyID"] = CurrentUser.getCountyID()
        jSONObject["DeviceModel"] = ""
        jSONObject["DeviceType"] = 3
        jSONObject["IP"] = iP
        jSONObject["MacAddr"] = ""
        jSONObject["Operation"] = Operations[OperationId]
        jSONObject["SchoolName"] = CurrentUser.getSchoolName()
        jSONObject["UserName"] = CurrentUser.getUserName()
        jSONObject["UserType"] = CurrentUser.getUserType()
        method.saveOperation(BASE_URL, jSONObject)
                .subscribe(Consumer { resp: ResponseBody? -> Log.e("====执行操作日志====", Operations[OperationId]) },
                        Consumer { e: Throwable? -> })
    }

    val iP: String?
        get() {
            try {
                val en = NetworkInterface.getNetworkInterfaces()
                while (en.hasMoreElements()) {
                    val intf = en.nextElement()
                    val enumIpAddr = intf.inetAddresses
                    while (enumIpAddr.hasMoreElements()) {
                        val inetAddress = enumIpAddr.nextElement()
                        if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                            return inetAddress.getHostAddress().toString()
                        }
                    }
                }
            } catch (ex: SocketException) {
                ex.printStackTrace()
            }
            return null
        }
}